import { Component, OnInit } from '@angular/core';
import {MsgResult} from "../../../../models/msg-result";
import {MsgConstants} from "../../../../constants/constants";
import {FormGroup, FormBuilder, Validators} from "@angular/forms";
import {Router, ActivatedRoute} from "@angular/router";
import {PageSubject} from "../../../../util/page-subject";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../../util/response-util";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {FormUtil} from "../../../../util/form-util";
import {DataDictionaryService} from "../../../../services/dataDictionary.service";
import {SiteDevices} from "../site-devices";
import {SiteDevicesService} from "../site-devices.service";

@Component({
  selector: 'app-site-devices-update',
  templateUrl: './site-devices-update.component.html',
  styleUrls: ['./site-devices-update.component.css']
})
export class SiteDevicesUpdateComponent implements OnInit {

  siteDevice : SiteDevices;

  siteDeviceForm : FormGroup;

  codMonitors;

  //设备使用状态
  useStatusArr: Array<string> = [];
  //设备运行状态
  workStatusArr: Array<string> = [];
  // 传输方式
  dicTransModeArr: Array<string> = [];

  constructor(
    private router :Router,
    private route :ActivatedRoute,
    private pageSubject : PageSubject,
    private fb : FormBuilder,
    private dialogService :OneDialogService,
    private responseUtil : ResponseUtil,
    private formUtil : FormUtil,
    private dataDictionaryService : DataDictionaryService,
    private siteDeviceService : SiteDevicesService
  ) {
    this.initObject();
  }

  ngOnInit() {
    this.pushPage();
    this.initMonitorUpdateForm();
    this.initMonitorType();
    this.initDataDictionary();
  }

  /**
   * 面包屑
   */
  pushPage(){
    let path =new Path("运维管理","");
    this.pageSubject.pushPage("设备管理","修改",path);
  }

  /**
   * 构造表单
   */

  /**
   * 构造表单
   */
  private buildForm():void{
    this.siteDeviceForm=this.fb.group({
      'id': [this.siteDevice.id],
      'snCode': [this.siteDevice.snCode,[
        Validators.required
      ]],
      'clientipinfClient': [this.siteDevice.clientipinfClient],
      'clientipinfServer': [this.siteDevice.clientipinfServer],
      'clientipinfTranster': [this.siteDevice.clientipinfTranster],
      'statusUse': [this.siteDevice.statusUse = '1'],
      'statusWork': [this.siteDevice.statusWork = '1'],
      'monitorCode': [this.siteDevice.monitorCode = "257",[
        Validators.required,
      ]],
      'mPhone': [this.siteDevice.mPhone,[
        Validators.maxLength(14),
        Validators.pattern(/(^(((13[0-9]{1})|(15[0-9]{1}))+\d{8})$)|(^\d{3,4}-?\d{7,9}$)/)
      ]],
      'remark': [this.siteDevice.remark,[
        Validators.maxLength(30)
      ]],
      'transMode': [this.siteDevice.transMode = "1",[
        Validators.maxLength(20)
      ]]
    });

    this.siteDeviceForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }

  private onValueChanged(data ?: any) {
    if (!this.siteDeviceForm) {
      return;
    }
    const form = this.siteDeviceForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'snCode': '',
    'monitorCode': '',
    'mPhone': '',
    'remark': '',
    'transMode': '',
  };

  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'snCode': {
      'required': '设备编号不能为空',
      'maxlength': '长度不能超过10',
      'pattern': '只能由字母、数字、下划线组成'
    },
    'monitorCode': {
      'required': '设备类型不能为空',
    },
    'mPhone': {
      'maxlength': '长度不能超过14位',
      'pattern': '格式不正确'
    },
    'remark': {
      'maxlength': '长度不能超过30位',
    },
    'transMode': {
      'required': '数据传输方式不能为空',
      'maxlength': '长度不能超过20位',
    },
  };

  /**
   * 根据id查询某设备的详细信息
   */
  initMonitorUpdateForm(){
    let id=this.route.snapshot.params["id"];
    if(!!id){
      this.siteDeviceService.getSiteMonitorById(id).subscribe(
        result =>this.responseUtil.success(result,this.processInitMonitorResult),
        error =>this.responseUtil.error(error)
      );
    }
  }

  /**
   * 处理根据id查询的结果；
   * 1.判断结果是否为空；
   * 2.不为空，把值赋予monitor对象；
   * 3.再把monitor对象放进构造表单；
   * @param result
   */
  private processInitMonitorResult =(result :MsgResult)=>{
    if(result && result.code == MsgConstants.MSG_CODE_OK){
      this.siteDevice =result.data;
      this.siteDeviceForm.patchValue(this.siteDevice);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 初始化设备类型，下拉框
   */
  private initMonitorType(){
    this.siteDeviceService.getMonitor().subscribe(
      result => this.responseUtil.success(result ,this.processMonitorResult),
      message => this.responseUtil.error(message)
    )
  }

  /**
   * 处理查询结果
   * @param result
   */
  private processMonitorResult =(result :MsgResult)=>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.codMonitors = result.data;
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 初始化数据字典数据
   */
  initDataDictionary(){
    this.dataDictionaryService.getChildDicByCode('SBGL').subscribe(
      result => this.responseUtil.success(result ,this.processDictionaryResult),
      message => this.responseUtil.error(message)
    )
  }

  /**
   * 处理查询结果
   * @param result
   */
  private processDictionaryResult =(result :MsgResult)=>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.workStatusArr = this.formUtil.filterDictionaryByCode('SBGL_SBZT',result.data);
      this.dicTransModeArr = this.formUtil.filterDictionaryByCode('SBGL_SJCSFS',result.data);
      this.useStatusArr= this.formUtil.filterDictionaryByCode('SBGL_SBSYZT',result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }



  /**
   * 实现修改
   */
  onSubmit() {
    this.siteDevice = this.siteDeviceForm.value;
    // console.log(JSON.stringify(this.siteDevice));
    this.siteDeviceService.siteMonitorEdit(this.siteDevice).subscribe(
      result => this.responseUtil.success(result, this.processSiteMonitorResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 获取修改结果
   * @param result
   */
  private processSiteMonitorResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.cancelSiteMonitorAdd();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 取消修改
   */
  cancelSiteMonitorAdd(){
    this.router.navigate(['..'],{relativeTo : this.route});
  }

  /**
   *
   */
  private initObject() {
    this.siteDevice = new SiteDevices();
    this.buildForm();
  }

}
